package cn.sell.comm.thread;

import com.alibaba.fastjson.JSON;

import java.util.concurrent.ConcurrentHashMap;

/**
 * 
 * @author wujian
 * 2018-05-03
 */
public class MyThreadLocal extends ConcurrentHashMap<String, Object> {
	private static final long serialVersionUID = 1L;

	protected static Class<? extends MyThreadLocal> contextClass = MyThreadLocal.class;

    private static MyThreadLocal testContext = null;

    private static final ThreadLocal<? extends MyThreadLocal> threadLocal = new ThreadLocal<MyThreadLocal>() {
        @Override
        protected MyThreadLocal initialValue() {
            try {
                return contextClass.newInstance();
            } catch (Throwable e) {
                throw new RuntimeException(e);
            }
        }
    };
	
    public static final String THREAD_DATA = "thread_data";
    public static final String TOKEN = "token";
    public static final String INSURANCE_SYSTEM = "insurance_system";

    public static MyThreadLocal getCurrentThread() {
        if (testContext != null) return testContext;
        MyThreadLocal context = threadLocal.get();
        return context;
    }

    public void removeAll(){
    	threadLocal.remove();
    }
    
    public static String toJson(ThreadData data){
		return JSON.toJSONString(data);
    }
    
    public static ThreadData toData(String json){
    	return JSON.parseObject(json, ThreadData.class);
    }
    
    public static class ThreadData{
    	
    	private String token; //对userInfo进行MD5加密
    	private String userInfo; //以AES对称加密成为字符串
    	private Object data; //请求方自定义数据
    	private String sessionId; //请求方自定义数据
    	
		public String getToken() {
			return token;
		}
		public void setToken(String token) {
			this.token = token;
		}
		public String getUserInfo() {
			return userInfo;
		}
		public void setUserInfo(String userInfo) {
			this.userInfo = userInfo;
		}
		public Object getData() {
			return data;
		}
		public void setData(Object data) {
			this.data = data;
		}
		public String getSessionId() {
			return sessionId;
		}
		public void setSessionId(String sessionId) {
			this.sessionId = sessionId;
		}
    }
    
    public static class UserInfo{
    	private Integer userId;
    	private String userName;
//    	private String password;
    	private Integer roleId;
		public Integer getUserId() {
			return userId;
		}
		public void setUserId(Integer userId) {
			this.userId = userId;
		}
		public String getUserName() {
			return userName;
		}
		public void setUserName(String userName) {
			this.userName = userName;
		}
		public Integer getRoleId() {
			return roleId;
		}
		public void setRoleId(Integer roleId) {
			this.roleId = roleId;
		}
    }
}
